package Controller;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import Tools.DOMUtilities;
import Tools.ModelGalleryEngine;
import Tools.XPathEngine;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author linhduong
 */
public class XMLRender extends HttpServlet {

    private String requestParser(HttpServletRequest request) {
        String search, browse;
        if((search = request.getParameter("search"))!=null) {
            if(search.isEmpty()) return "empty";
            return ModelGalleryEngine.searchPictures(search);
        } else
        if((browse = request.getParameter("browse"))!=null) {
            if(browse.isEmpty()) return "empty";
            String query = ModelGalleryEngine.browseAlbum(browse);
            if(query==null) return "empty";
            return query;
        }
        return null;
    }


    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/xml");
        PrintWriter out = response.getWriter();
        out.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        out.print("<root>");
        try {

            String requestP = requestParser(request);

            if(requestP==null) {
                out.print("<error/></root>");
                out.close(); return;
            }

            if(request.getParameter("browse")!=null) out.print("<path>" + request.getParameter("browse") + "</path>");

            if(requestP.equals("empty")) {
                out.print("<empty/></root>");
                out.close(); return;
            }

            String path = getServletContext().getRealPath("") + getServletContext().getInitParameter("modelXML");
            NodeList nodes = XPathEngine.queryDocument(DOMUtilities.parsedFromXML(path), requestP);
            
            for (int i = 0; i < nodes.getLength(); i++) {
                Node node = nodes.item(i);
                String urlPath = ModelGalleryEngine.getPathUrlOf(node);
                if(node.getNodeName().equals("Picture")) {
                    String thumb = "photos/" + urlPath + node.getAttributes().getNamedItem("thumb").getNodeValue();
                    String src = "photos/" + urlPath + node.getAttributes().getNamedItem("src").getNodeValue();
                    out.print("<Picture href=\""+ src + "\" thumb=\""+thumb+"\"/>");
                } else
                if(node.getNodeName().equals("Album")) {
                    String thumb = node.getAttributes().getNamedItem("thumb").getNodeValue();
                    String src = urlPath + node.getAttributes().getNamedItem("id").getNodeValue();
                    out.print("<Album href=\""+ src + "\" thumb=\""+thumb+"\"/>");
                }
            }
            out.print("</root>");
        }
        catch(Exception e) {
            out.println("<error>"+e.getMessage()+"</error>");
            out.println("</root>");
        }
        finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
